package com.org.cys.util;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;

/**
 * Spring MVC 导出Excel
 * @author caiyushen
 * */
public class ExportExcel extends AbstractExcelView{
	
	@Override
	protected void buildExcelDocument(Map<String, Object> model,HSSFWorkbook workbook, HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		Date date = new Date();
		String filename = DateUtil.date2Str(date,"yyyyMMddHHmmss");
		
		HSSFSheet sheet; //工作表
		HSSFCell cell;	 //cell
		
		//设置返回response参数
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", "attachment;filename="+filename+".xls"); //文件名
		
		sheet = workbook.createSheet("sheet1");//创建一个工作表
		
		List<String> titles = (List<String>) model.get("titles"); //获取标题数据，作为列名称
		
		int len = titles.size();//标题数即列总数
		
		HSSFCellStyle headerStyle = workbook.createCellStyle(); //标题样式
		headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);	//水平居中
		headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直居中
		HSSFFont headerFont = workbook.createFont();	//标题字体
		headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//字体加粗 
		headerFont.setFontHeightInPoints((short)11); //字体大小
		headerStyle.setFont(headerFont); //设置标题字体样式
		short width = 20,height=25*20; //设置长宽高
		sheet.setDefaultColumnWidth(width); //设置格子默认宽度
		for(int i=0; i<len; i++){ //设置标题
			String title = titles.get(i);
			cell = getCell(sheet, 0, i); //getCell(工作表，行数，列数)
			cell.setCellStyle(headerStyle);//加入标题样式
			setText(cell,title);//标题内容填充到对应位置
		}
		sheet.getRow(0).setHeight(height);//设置第一行高度
		
		HSSFCellStyle contentStyle = workbook.createCellStyle(); //内容样式
		contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平居中
		
		List<PageData> varList = (List<PageData>) model.get("varList");//获取具体内容数据
		int varCount = varList.size();//去内容数为内容的行总数
		for(int i=0; i<varCount; i++){
			PageData vpd = varList.get(i); //获取内容数据
			for(int j=0;j<len;j++){
				String varstr = vpd.getString("var"+(j+1)) != null ? vpd.getString("var"+(j+1)) : "";
				cell = getCell(sheet, i+1, j);//getCell(工作表，行数，列数) 因为已经有了第一行作为标题所以i+1
				cell.setCellStyle(contentStyle);//加入内容样式
				setText(cell,varstr);//内容数据填充到对应位置
			}
			
		}
		
		
	}
	
}